﻿/// <reference path="../../../plugins/layui/plugins/eleTree/eleTree.js" />
/// <reference path="../../../plugins/layui/plugins/eleTree/eleTree.js" />
$(function () {
    //2.初始化页面
    var oPageInit = new PageInit();
    oPageInit.Init();
});

var PageInit = function () {
    var oInit = new Object();
    var postdata = {};

    var table, form, layer, tree, eleTree, util;
    var el;
    var active;
    var tableId = 'tb_list';

    //初始化页面上面的按钮事件
    oInit.Init = function () {
        layui.use(['table', 'tree', 'util'], function () {
            table = layui.table
          , tree = layui.tree
          , util = layui.util
          , form = layui.form
          , layer = layui.layer;
            oInit.loadData();
        })

        //layui.config({
        //    base: Root + 'Content/plugins/layui/plugins/eleTree/'
        //}).use(['eleTree'], function () {
        //    debugger
        //    eleTree = layui.eleTree;
        //});

        $('#btnSearchMenu').click(function () {
            var openIndex = layer.open({
                title: '选中菜单',
                type: 1,
                area: ['60%', '80%'],
                maxmin: true,
                shadeClose: true,
                //closeBtn: false,  //右上角关闭按钮
                content: $('#menuDiv'),
                shade: 0.5, // 显示遮罩程度0-1
                //btnAlign: 'c',
                moveType: 1, //拖拽模式，0或者1
                success: function (layero, index) {
                    //获得当前用户的菜单节点，并选中对应的菜单
                    var txtMenuIds = $('#txtMenuIds').val();
                    //取出转数组
                    let checkData = txtMenuIds.split(',');
                    let intCheckData = [];
                    checkData.forEach(item => {
                        intCheckData.push(+item);
                    });

                    tree.setChecked('menuDiv', intCheckData); //批量勾选节点
                    //el.setChecked(intCheckData, true); //批量勾选节点
                }
                , btn: ['保存', '关闭']
                , yes: function () {
                    //获得选中的节点
                    //var checkData = el.getChecked(false, true);
                    var checkData = tree.getChecked('menuDiv');
                    //console.log(checkData);
                    //将数据赋值文本框中
                    checkIds = '';
                    titleIds = '';
                    oInit.GetSubTree(checkData, false);
                    layer.close(openIndex);
                }
                , btn2: function () {
                    layer.close(openIndex);
                }
            });
        });
    }

    var checkIds = '';
    var titleIds = '';
    oInit.GetSubTree = function (childrens, isAdd) {
        for (var item in childrens) {
            if (isAdd) {
                checkIds += childrens[item].id + ',';
                titleIds += childrens[item].title + ',';
            }
            oInit.GetSubTree(childrens[item].children, true);
        }
        //console.log(checkIds)
        //console.log(titleIds)
        $('#txtMenuIds').val(checkIds);
        $('#txtMenuNames').val(titleIds);
    }

    //初始化Table,加载数据
    oInit.loadData = function () {
        //方法级渲染
        table.render({
            elem: '#' + tableId
            , id: tableId
        , loading: true
        , toolbar: '#toolbar'
        , defaultToolbar: ['']  //工具栏右侧的图标按钮
        , url: Root + 'FZRole/GetSysRole'
        , cols: [[
        { checkbox: true, fixed: true }, { type: 'numbers', title: '序号' }
        , {
            field: 'name',
            title: '角色名称'
        }, {
            field: 'code',
            title: '角色编码'
        }, {
            field: 'descs',
            title: '角色描述'
        }, {
            field: 'menuNames',
            title: '角色菜单',
            width: '40%'
        }, {
            field: 'updatetime',
            title: '创建时间',
            width: 110,
            templet: function (row) {
                return row.updatetime == null ? '' : changeDateFormat(row.updatetime)
            }
        }
        , { fixed: 'right', title: '操作', toolbar: '#tableBar', width: 120 }
        ]]
        , page: true
        , limit: 10
            //, cellMinWidth: 80
        , height: 'full-300'
        });

        var $ = layui.$;
        active = {
            reload: function () {
                var txt_search = $('#txt_search');
                var temp = {
                    SearchText: txt_search.val(),
                };

                //执行重载
                table.reload(tableId, {
                    method: 'post',
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                  , where: temp
                }, 'data');
            }
        };

        $('#formSearch .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //监听工具条增删改按钮
        zpActive.tableTool(table, layer, form, null, null, null, null, null, oInit.Delete, null);

        //监听提交按钮
        form.on('submit(save)', function (data) {
            var rs = oInit.Save(data.field);    //保存数据
            if (rs) {
                active.reload();    //重新加载table数据
                layer.closeAll();   //关闭弹出层
            }
            return false;   //true刷新当前页面
        });

        oInit.LoadMenu();
    }

    //保存-新增
    oInit.Save = function (formdata) {
        //var dto = decodeURIComponent(formdata, true);   //处理中文,后台需要解码
        var result = false;
        //静态添加节点
        $.ajax({
            type: "post",
            url: Root + 'FZRole/SaveSysRole',
            async: false,
            data: { dto: formdata },
            success: function (data) {
                if (data.SubmitResult) {
                    result = true;
                } else {
                    dialog.danger('操作失败！Error Message:' + data.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {

            }
        });
        return result;
    }

    //删除
    oInit.Delete = function (arr_obj) {
        for (var i = 0; i < arr_obj.length; i++) {
            if (arr_obj[i].id == 1 || arr_obj[i].type == "超级管理员") {
                dialog.warning('超级管理员不能删除！');
                return;
            }
        }

        $.ajax({
            type: "post",
            url: Root + 'FZRole/DeleteSysRole',
            data: { dto: arr_obj },
            success: function (data) {
                if (data.SubmitResult) {
                    dialog.success('删除成功');
                    active.reload();
                } else {
                    dialog.danger('操作失败！Error Message:' + data.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {

            }
        });
    }

    //加载下拉菜单数据
    oInit.LoadMenu = function () {
        //所有菜单data
        var data = {};

        $.ajax({
            type: "post",
            async: false,
            url: Root + 'FZMenu/GetMenuTreeJson',
            success: function (result) {
                if (result && result.length > 0) {
                    //console.log(result)
                    data = result;
                } else {
                    dialog.danger('操作失败！Error Message:' + data.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {

            }
        });

        //tree基本演示
        tree.render({
            elem: '#menuDiv'
          , data: data
          , showCheckbox: true  //是否显示复选框
          , id: 'menuDiv'
          , isJump: false //是否允许点击节点时弹出新窗口跳转
          , click: function (obj) {
              var data = obj.data;  //获取当前点击的节点数据
              layer.msg('状态：' + obj.state + '<br>节点数据：' + JSON.stringify(data));
          }
        });

        //eleTree
        //el = eleTree({
        //    el: '#menuDiv',
        //    //url: Root + 'FZMenu/GetMenuTreeJson',
        //    data: data,
        //    highlightCurrent: true,
        //    showCheckbox: true,
        //})
    }
    return oInit;
}